package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import beans.*;

public class ModelDao {

    /**
     *
     * @param isAll true:查询所有模型     false:只查询默认模型
     * @param detail    true:查询所有模型细节   false:除去模型json和nest_json
     * @return
     */
    public List<Object> getAllModel(boolean isAll, boolean detail) {
        String sql = "";
        if(isAll){
            sql = "select * from model,user where model.create_person=user.user_id order by model_id desc";
        }else{
            sql = "select * from model,user where model.create_person=user.user_id and is_default = 1 order by model_id desc";
        }
        return modelDetail(detail,sql,null);
    }



    public List<Object> modelDetail(final boolean detail, String sql, Object[] params){
        final List<Object> results = new ArrayList<>();
        return Query.executeQueryList(results, sql,params, new QueryCallBackList() {
            @Override
            public List<Object> doExecuteList(ResultSet rs, List<Object> results) {
                try {
                    while (rs.next()) {
                        if(detail){
                            results.add(packModelDetail(rs));
                        }else{
                            results.add(packModelOverview(rs));
                        }
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return results;
            }
        });
    }
    //查询模型信息   By李金鑫
	public List<Object> getModelByModelId(String modelId) {
        String sql = "select * from model,user where model.create_person=user.user_id and model_id = ? order by model_id desc";
        return modelDetail(true, sql,new Object[]{modelId});

    }

    private Model packModelOverview(ResultSet rs) throws SQLException {
        Model model = new Model();
        model.setCreatePerson(rs.getString("user_name"));
        model.setCreateTime(rs.getString("create_time"));
        model.setIntroduction(rs.getString("introduction"));
        model.setIsNesting(rs.getBoolean("is_nesting"));
        model.setIsReuse(rs.getBoolean("is_reuse"));
        model.setModelId(rs.getInt("model_id"));
        model.setName(rs.getString("model_name"));
        model.setDefault(rs.getBoolean("is_default"));
        return model;
    }

    private Model packModelDetail(ResultSet rs) throws SQLException {
        Model model = new Model();
        model.setCreatePerson(rs.getString("user_name"));
        model.setCreateTime(rs.getString("create_time"));
        model.setIntroduction(rs.getString("introduction"));
        model.setIsNesting(rs.getBoolean("is_nesting"));
        model.setIsReuse(rs.getBoolean("is_reuse"));
        model.setJson(rs.getString("json"));
        model.setModelId(rs.getInt("model_id"));
        model.setName(rs.getString("model_name"));
        model.setNest_json(rs.getString("nest_json"));
        model.setDefault(rs.getBoolean("is_default"));
        model.setAlgorithm_id(rs.getInt("algorithm_id"));
        return model;
    }

    public List<Object> getModels(Integer onePageCount, Integer currentPage) {
        String sql = "select * from model left join user on model.create_person=user.user_id  order by model_id desc limit " + (currentPage - 1) * onePageCount + " , " + onePageCount;
        return modelDetail(true,sql,null);
    }

    public int getModelPageNum(Integer onePageCount) {
        int modelNum = this.modelNum();
        return (modelNum % onePageCount) == 0 ? (modelNum / onePageCount) : (modelNum / onePageCount + 1);
    }
    public int modelNum() {
        String sql = "select count(*) from model ";
        return PublicDao.oneNum(sql,null);
    }
//
//    //添加模型    By尹行
//    public Boolean addModel(String name, String create_person, String create_time, Integer is_nesting
//            , String nest_json, String json, Integer is_reuse, String introduction) {
//        String sql = "INSERT INTO `model` (`model_name`, `create_person`, `create_time`, `is_nesting`, "
//                + "`json`, `introduction`, `nest_json`, `is_reuse`) " +
//                "VALUES ('"+name+"', '"+create_person+"', '"+create_time+"', "+is_nesting+", '"+json
//                +"', '"+introduction+"', '"+nest_json+"', "+is_reuse+")";
//        //返回结果
//        int resultNum = Query.executeDML(sql, null);
//        boolean result = (resultNum == -1)?false:true;
//        return result;
//    }

    /**
     * 添加创建模型的方法，为算法创建默认模型的时候将算法id存进去
     * 2018-10-30 朱耀堃添加
     * @param name
     * @param create_person
     * @param create_time
     * @param is_nesting
     * @param nest_json
     * @param json
     * @param is_reuse
     * @param introduction
     * @param isDefault
     * @return
     */
    public List<Object> addModelAndAlgorithmId(String algorithmId,String name, String create_person, String create_time, Integer is_nesting
            , String nest_json, String json, Integer is_reuse, String introduction, Integer isDefault) {
        String sql = "INSERT INTO `model` (`model_name`, `create_person`, `create_time`, `is_nesting`, "
                + "`json`, `introduction`, `nest_json`, `is_reuse`, `is_default`, `algorithm_id`) " +
                "VALUES (?, ?, now(), ?, ?, ?, ?, ?, ?,?)";
        Object[] params = new Object[]{name,create_person,is_nesting,json,introduction,nest_json,is_reuse,isDefault,algorithmId};
        //返回结果
        List<Object> results = new ArrayList<>();
        results = PublicDao.generateKeys(results,sql,params);
        if (results.size() > 0)

        {
            return results;
        } else

        {
            return null;
        }
    }

    public boolean updateModelJsonAndIntroduction(String json,String introduction, int modelId) {
        String sql = "UPDATE `model` SET json=?, introduction=? WHERE `model_id`=?";
        Object[] params = new Object[]{json, introduction, modelId};
        //返回结果
        List<Object> results = new ArrayList<>();
        int resultNum = Query.executeDML(sql, params);
        boolean result = (resultNum == -1)?false:true;
        return result;
    }

    //添加模型    By zhuyaokun
    public List<Object> addModelReturnId(String name, String create_person, String create_time, Integer is_nesting
            , String nest_json, String json, Integer is_reuse, String introduction, Integer isDefault) {
        String sql = "INSERT INTO `model` (`model_name`, `create_person`, `create_time`, `is_nesting`, "
                + "`json`, `introduction`, `nest_json`, `is_reuse`, `is_default`) " +
                "VALUES ('"+name+"', '"+create_person+"', now(), "+is_nesting+", '"+json
                +"', '"+introduction+"', '"+nest_json+"', "+is_reuse+", "+ isDefault +")";
        //返回结果
        List<Object> results = new ArrayList<>();
        results = PublicDao.generateKeys(results,sql,null);
        if (results.size() > 0)

        {
            return results;
        } else

        {
            return null;
        }
    }

    public List<Object> addModelByModelReturnId(Model model) {
        String sql = "INSERT INTO `model` (`model_name`, `create_person`, `create_time`, `is_nesting`, "
                + "`json`, `introduction`, `nest_json`, `is_reuse`, `is_default`) " +
                "VALUES (?, ?, now(), ?, ?, ?, ?, ?, ?)";
        //返回结果
        List<Object> results = new ArrayList<>();
        Object[] params = new Object[]{model.getName(),model.getCreatePerson(),model.isNesting,model.getJson()
                ,model.getIntroduction(),model.getNest_json(),model.getIsReuse(),model.isDefault()};
        results = PublicDao.generateKeys(results,sql,params);
        if (results.size() > 0)

        {
            return results;
        } else

        {
            return null;
        }
    }

    //删除模型   By尹行
    public Boolean deleteModel(String model_id) {
        String sql = "delete from model where model_id =" + model_id;
        //返回结果
        int resultNum = Query.executeDML(sql, null);
        boolean result = (resultNum == -1)?false:true;
        return result;
    }

    //修改模型   By尹行
    public Boolean alterModel(String model_id, String name, String create_person, String create_time, Integer is_nesting
            , String nest_json, String json, Integer is_reuse, String introduction) {
        String sql = "UPDATE `model` SET `model_id`="+model_id+", `model_name`='"+name+"', `create_person`='"+create_person+"'," +
                " `is_nesting`="+is_nesting+", `json`='"+json+"', `introduction`='"+introduction+"'," +
                " `nest_json`='"+nest_json+"', `is_reuse`="+is_reuse+" WHERE `model_id`="+model_id;
        //返回结果
        int resultNum = Query.executeDML(sql, null);
        boolean result = (resultNum == -1)?false:true;
        return result;
    }

    public int getModelIdByAlgorithmId(String autoAlgorithmId) {
        String sql = "select `model_id` from `model` where `algorithm_id` = ?";
        Object[] param = new Object[]{autoAlgorithmId};
        int result = (int) Query.executeQueryObject(sql, param, new QueryCallBack() {
            @Override
            public Object doExecute(ResultSet rs) {
                int result = -1;
                try {
                    while (rs.next()) {
                        result =  rs.getInt("model_id");
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return result;
            }
        });
        return result;
    }
}